from flask import Flask, render_template, request, jsonify, session, redirect, url_for
from werkzeug.security import generate_password_hash, check_password_hash
import os
import sys
import uuid
from datetime import datetime, timedelta

# 添加src目录到Python路径
sys.path.append(os.path.join(os.path.dirname(__file__), 'src'))

from database.database_manager import DatabaseManager
from account.account_manager import AccountManager
from character.mysql_character_manager import MySQLCharacterManager
from idle.mysql_idle_manager import MySQLIdleManager

app = Flask(__name__)
app.secret_key = 'vxbattle_secret_key_2024'  # 在生产环境中应该使用环境变量

# 初始化管理器
db_manager = DatabaseManager()
account_manager = AccountManager()
character_manager = MySQLCharacterManager()
idle_manager = MySQLIdleManager()

@app.route('/')
def index():
    """主页"""
    if 'user_id' in session:
        return redirect(url_for('dashboard'))
    return render_template('index.html')

@app.route('/login', methods=['GET', 'POST'])
def login():
    """登录页面"""
    if request.method == 'POST':
        data = request.get_json()
        username = data.get('username')
        password = data.get('password')
        
        try:
            # 验证用户
            success, message, account = account_manager.login(username, password)
            if success and account:
                session['user_id'] = account.account_id
                session['username'] = account.username
                return jsonify({'success': True, 'message': '登录成功'})
            else:
                return jsonify({'success': False, 'message': message or '用户名或密码错误'})
        except Exception as e:
            return jsonify({'success': False, 'message': f'登录失败: {str(e)}'})
    
    return render_template('login.html')

@app.route('/register', methods=['GET', 'POST'])
def register():
    """注册页面"""
    if request.method == 'POST':
        data = request.get_json()
        username = data.get('username')
        password = data.get('password')
        email = data.get('email', '')
        
        try:
            # 注册用户
            success, message, account = account_manager.create_account(username, email, password)
            if success and account:
                return jsonify({'success': True, 'message': '注册成功，请登录'})
            else:
                return jsonify({'success': False, 'message': message or '注册失败，用户名可能已存在'})
        except Exception as e:
            return jsonify({'success': False, 'message': f'注册失败: {str(e)}'})
    
    return render_template('register.html')

@app.route('/logout')
def logout():
    """登出"""
    session.clear()
    return redirect(url_for('index'))

@app.route('/dashboard')
def dashboard():
    if 'user_id' not in session:
        return redirect(url_for('login'))
    return render_template('dashboard.html')

# API路由
@app.route('/api/characters')
def api_characters():
    if 'user_id' not in session:
        return jsonify({'success': False, 'message': '未登录'}), 401
    
    try:
        # 设置角色管理器的账号ID
        character_manager.set_account_id(session['user_id'])
        characters = character_manager.get_characters_by_account(session['user_id'])
        character_list = []
        for char in characters:
            # 检查角色是否在挂机
            idle_status = idle_manager.get_idle_status(char.char_id)
            is_idle = idle_status is not None
            
            character_list.append({
                'id': char.char_id,
                'name': char.name,
                'character_class': char.char_class.value if hasattr(char.char_class, 'value') else char.char_class,
                'level': char.level,
                'exp': char.exp,
                'exp_to_next_level': char.get_exp_for_next_level(),
                'hp': char.hp,
                'mp': char.mp,
                'attack': char.attack,
                'defense': char.defense,
                'speed': char.speed,
                'status': char.status.value if hasattr(char.status, 'value') else char.status,
                'is_idle': is_idle
            })
        return jsonify({'success': True, 'characters': character_list})
    except Exception as e:
        return jsonify({'success': False, 'message': str(e)}), 500

@app.route('/api/characters/create', methods=['POST'])
def api_create_character():
    if 'user_id' not in session:
        return jsonify({'success': False, 'message': '未登录'}), 401
    
    try:
        data = request.get_json()
        name = data.get('name', '').strip()
        character_class = data.get('character_class', '').strip()
        
        if not name or not character_class:
            return jsonify({'success': False, 'message': '角色名称和职业不能为空'})
        
        if len(name) < 2 or len(name) > 20:
            return jsonify({'success': False, 'message': '角色名称长度必须在2-20个字符之间'})
        
        # 检查角色名是否已存在
        existing_chars = character_manager.get_characters_by_account(session['user_id'])
        for char in existing_chars:
            if char.name == name:
                return jsonify({'success': False, 'message': '角色名称已存在'})
        
        # 设置角色管理器的账号ID
        user_id = session['user_id']
        print(f"DEBUG: session中的user_id = {user_id}, 类型: {type(user_id)}")
        character_manager.set_account_id(user_id)
        
        # 创建角色
        success, message, character = character_manager.create_character(
            name=name,
            character_class=character_class
        )
        
        if success and character:
            # 角色创建后自动开始挂机
            idle_success, idle_message = idle_manager.start_idle(character.char_id)
            
            # 即使挂机失败也返回角色创建成功
            return jsonify({
                'success': True, 
                'message': message + (f"，并自动开始挂机" if idle_success else ""),
                'character_id': character.char_id
            })
        else:
            return jsonify({
                'success': False,
                'message': message
            })
    except Exception as e:
        return jsonify({'success': False, 'message': str(e)}), 500

@app.route('/api/characters/<character_id>/delete', methods=['DELETE'])
def api_delete_character(character_id):
    if 'user_id' not in session:
        return jsonify({'success': False, 'message': '未登录'}), 401
    
    try:
        # 转换character_id为整数
        character_id = int(character_id)
        
        # 设置角色管理器的账号ID
        character_manager.set_account_id(session['user_id'])
        
        # 验证角色属于当前用户
        character = character_manager.get_character_by_id(character_id)
        if not character or character.account_id != session['user_id']:
            return jsonify({'success': False, 'message': '角色不存在或无权限'}), 403
        
        # 检查角色是否正在挂机
        idle_status = idle_manager.get_idle_status(character_id)
        if idle_status and idle_status.get('is_idle', False):
            return jsonify({'success': False, 'message': '角色正在挂机中，请先停止挂机再删除'}), 400
        
        # 删除角色
        success, message = character_manager.delete_character(character_id)
        
        if success:
            return jsonify({
                'success': True,
                'message': message or '角色删除成功'
            })
        else:
            return jsonify({
                'success': False,
                'message': message or '删除角色失败'
            })
    except ValueError:
        return jsonify({'success': False, 'message': '无效的角色ID'}), 400
    except Exception as e:
        return jsonify({'success': False, 'message': str(e)}), 500

@app.route('/api/character/classes')
def api_character_classes():
    """获取角色职业模板"""
    try:
        query = """
        SELECT class_name, class_name_en, description, 
               base_hp, base_mp, base_attack, base_defense, base_speed,
               hp_growth, mp_growth, attack_growth, defense_growth, speed_growth
        FROM character_class_templates 
        ORDER BY id
        """
        templates = db_manager.execute_query(query)
        
        class_list = []
        for template in templates:
            class_list.append({
                'name': template['class_name'],
                'name_en': template['class_name_en'],
                'description': template['description'],
                'base_stats': {
                    'hp': template['base_hp'],
                    'mp': template['base_mp'],
                    'attack': template['base_attack'],
                    'defense': template['base_defense'],
                    'speed': template['base_speed']
                },
                'growth': {
                    'hp': float(template['hp_growth']),
                    'mp': float(template['mp_growth']),
                    'attack': float(template['attack_growth']),
                    'defense': float(template['defense_growth']),
                    'speed': float(template['speed_growth'])
                }
            })
        
        return jsonify({'success': True, 'classes': class_list})
    except Exception as e:
        return jsonify({'success': False, 'message': str(e)}), 500

@app.route('/api/idle/locations')
def api_idle_locations():
    if 'user_id' not in session:
        return jsonify({'success': False, 'message': '未登录'}), 401
    
    try:
        locations = idle_manager.get_idle_locations()
        location_list = []
        for loc in locations:
            location_list.append({
                'id': loc['id'],
                'name': loc['name'],
                'description': loc['description'],
                'min_level': loc['min_level'],
                'max_level': loc['max_level'],
                'base_exp_rate': loc['base_exp_rate']
            })
        return jsonify({'success': True, 'locations': location_list})
    except Exception as e:
        return jsonify({'success': False, 'message': str(e)}), 500

@app.route('/api/idle/status/<character_id>')
def api_idle_status(character_id):
    if 'user_id' not in session:
        return jsonify({'success': False, 'message': '未登录'}), 401
    
    try:
        # 转换character_id为整数
        character_id = int(character_id)
        
        # 设置角色管理器的账号ID
        character_manager.set_account_id(session['user_id'])
        # 验证角色属于当前用户
        character = character_manager.get_character_by_id(character_id)
        if not character or character.account_id != session['user_id']:
            return jsonify({'success': False, 'message': '角色不存在或无权限'}), 403
        
        idle_data = idle_manager.get_idle_status(character_id)
        return jsonify({'success': True, 'idle_data': idle_data})
    except ValueError:
        return jsonify({'success': False, 'message': '无效的角色ID'}), 400
    except Exception as e:
        return jsonify({'success': False, 'message': str(e)}), 500

@app.route('/api/idle/start', methods=['POST'])
def api_start_idle():
    if 'user_id' not in session:
        return jsonify({'success': False, 'message': '未登录'}), 401
    
    try:
        data = request.get_json()
        character_id = int(data.get('character_id'))
        location_id = int(data.get('location_id', 1))
        
        # 设置角色管理器的账号ID
        character_manager.set_account_id(session['user_id'])
        # 验证角色属于当前用户
        character = character_manager.get_character_by_id(character_id)
        if not character or character.account_id != session['user_id']:
            return jsonify({'success': False, 'message': '角色不存在或无权限'}), 403
        
        result = idle_manager.start_idle(character_id, location_id)
        if result:
            return jsonify({'success': True, 'message': '开始挂机成功！'})
        else:
            return jsonify({'success': False, 'message': '开始挂机失败'})
    except (ValueError, TypeError):
        return jsonify({'success': False, 'message': '无效的参数'}), 400
    except Exception as e:
        return jsonify({'success': False, 'message': str(e)}), 500

@app.route('/api/idle/collect_rewards', methods=['POST'])
def api_collect_idle_rewards():
    if 'user_id' not in session:
        return jsonify({'success': False, 'message': '未登录'}), 401
    
    try:
        data = request.get_json()
        character_id = int(data.get('character_id'))
        
        # 设置角色管理器的账号ID
        character_manager.set_account_id(session['user_id'])
        # 验证角色属于当前用户
        character = character_manager.get_character_by_id(character_id)
        if not character or character.account_id != session['user_id']:
            return jsonify({'success': False, 'message': '角色不存在或无权限'}), 403
        
        success, message, rewards = idle_manager.stop_idle(character_id)
        if success:
            return jsonify({
                'success': True, 
                'message': '收集挂机收益成功！',
                'rewards': rewards
            })
        else:
            return jsonify({'success': False, 'message': message})
    except (ValueError, TypeError):
        return jsonify({'success': False, 'message': '无效的角色ID'}), 400
    except Exception as e:
        return jsonify({'success': False, 'message': str(e)}), 500



if __name__ == '__main__':
    # 确保数据库连接正常
    try:
        db_manager.create_stored_procedures()
        print("数据库连接成功，存储过程已创建")
    except Exception as e:
        print(f"数据库初始化警告: {e}")
    
    app.run(debug=True, host='0.0.0.0', port=5000)